from timeloop import Timeloop
from threading import Thread
from linuxfd import timerfd


class period_task(Thread):
    def __init__(self,name,period):
        Thread.__init__(self)
        self.name = name
        self.period = period
        self.is_running = False

    def start(self):
        if self.is_running:
            print("[PeriodicTask]"+self.name+"is already running")
            return
        self.init()
        self.is_running = True
        Thread.start(self)

    def stop(self):
        if not self.is_running:
            print("[PeriodicTask]"+self.name+"is already not running")
            return
        self.is_running = False
        print("[PeriodicTask] Waiting for",self.name,"to stop")
        Thread.join(self)
        self.clean_up()
        print("[PeriodicTask] Done!")


    def run(self):
        timer_fd = timerfd()
        timer_fd.settime(self.period, self.period)
        while self.is_running:
            self.run_once()
            timer_fd.read()

    def init(self):
        # print("period task init")
        pass

    def run_once(self):
        pass

    def clean_up(self):
        pass